﻿using YunSpace.Application.SystemManage;
using YunSpace.Core;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace YunSpace.Web
{
    public class HandlerAuthorizeAttribute : ActionFilterAttribute
    {
        public bool Ignore { get; set; }

        public HandlerAuthorizeAttribute(bool ignore = true)
        {
            Ignore = ignore;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var currentProvider = OperatorProvider.Provider.GetCurrent();

            if (currentProvider == null)
            {
                filterContext.Result = new ContentResult()
                {
                    Content = "<script>location.href = '/Login/Login';</script>"
                };
                return;
            }

            if (currentProvider.IsSystem) return;

            if (Ignore == false) return;

            if (ActionAuthorize(filterContext)) return;

            filterContext.Result = new ContentResult()
            {
                Content = "<script type='text/javascript'>alert('很抱歉！您的权限不足，访问被拒绝！');</script>"
            };
        }
        private static bool ActionAuthorize(ActionExecutingContext filterContext)
        {
            var operatorProvider = OperatorProvider.Provider.GetCurrent();
            var roleId = operatorProvider.RoleId;
            var moduleId = WebHelper.GetCookie("YunSpace_currentmoduleid");
            var action = HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString();
            return new RoleAuthorizeApp().ActionValidate(roleId, moduleId, action);
        }


    }
}